package top.yueyazhui.vhr.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.*;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import top.yueyazhui.vhr.bean.Response;
import top.yueyazhui.vhr.component.UserFilterInvocationSecurityMetadataSource;
import top.yueyazhui.vhr.component.UserUrlDecisionManager;
import top.yueyazhui.vhr.filter.JwtFilter;
import top.yueyazhui.vhr.filter.JwtLoginFilter;
import top.yueyazhui.vhr.filter.VerificationCodeFilter;
import top.yueyazhui.vhr.model.Hr;
import top.yueyazhui.vhr.service.HrService;
import top.yueyazhui.vhr.util.IPUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    HrService hrService;
    @Autowired
    UserFilterInvocationSecurityMetadataSource userFilterInvocationSecurityMetadataSource;
    @Autowired
    UserUrlDecisionManager userUrlDecisionManager;
    @Autowired
    VerificationCodeFilter verificationCodeFilter;

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(hrService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(verificationCodeFilter, UsernamePasswordAuthenticationFilter.class);
        http.authorizeRequests()
//                .anyRequest().authenticated()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setAccessDecisionManager(userUrlDecisionManager);
                        object.setSecurityMetadataSource(userFilterInvocationSecurityMetadataSource);
                        return object;
                    }
                })
                .and()
                .formLogin()
                .usernameParameter("username")
                .passwordParameter("password")
                .loginProcessingUrl("/login")
                .loginPage("/login")
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        String ipAddress = IPUtil.getIpAddress(request);
                        System.out.println("ipAddress = " + ipAddress);
                        response.setContentType("application/json;charset=utf-8");
                        PrintWriter writer = response.getWriter();
                        Hr hr = (Hr) authentication.getPrincipal();
                        hr.setPassword(null);
                        Response success = Response.success("登录成功！", hr);
                        String s = new ObjectMapper().writeValueAsString(success);
                        writer.write(s);
                        writer.flush();
                        writer.close();
                    }
                })
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
                        response.setContentType("application/json;charset=utf-8");
                        PrintWriter writer = response.getWriter();
                        Response error = Response.error("登录失败！");
                        if (exception instanceof LockedException) {
                            error.setMessage("账户被锁定，请联系管理员！");
                        } else if (exception instanceof CredentialsExpiredException) {
                            error.setMessage("密码过期，请联系管理员！");
                        } else if (exception instanceof AccountExpiredException) {
                            error.setMessage("账户过期，请联系管理员！");
                        } else if (exception instanceof DisabledException) {
                            error.setMessage("账户被禁用，请联系管理员！");
                        } else if (exception instanceof BadCredentialsException) {
                            error.setMessage("用户名或密码输入错误！");
                        }
                        String s = new ObjectMapper().writeValueAsString(error);
                        writer.write(s);
                        writer.flush();
                        writer.close();
                    }
                })
                .permitAll()
                .and()
                .logout()
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        response.setContentType("application/json;charset=utf-8");
                        PrintWriter writer = response.getWriter();
                        Response success = Response.success("注销成功！");
                        String s = new ObjectMapper().writeValueAsString(success);
                        writer.write(s);
                        writer.flush();
                        writer.close();
                    }
                })
                .permitAll()
                .and()
//                .addFilterBefore(new JwtLoginFilter("/login", authenticationManager()), UsernamePasswordAuthenticationFilter.class)
//                .addFilterBefore(new JwtFilter(), UsernamePasswordAuthenticationFilter.class)
                .csrf().disable()
                // 没有认证时，在这里处理结果，不要重定向
                .exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {
                    @Override
                    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
                        response.setContentType("application/json;charset=utf-8");
                        response.setStatus(401);
                        PrintWriter writer = response.getWriter();
                        Response error = Response.error("访问失败！");
                        if (authException instanceof InsufficientAuthenticationException) {
                            error.setMessage("尚未登录，请登录！");
                        }
                        String s = new ObjectMapper().writeValueAsString(error);
                        writer.write(s);
                        writer.flush();
                        writer.close();
                    }
                });
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                // swagger
                .antMatchers("/swagger-ui.html")
                .antMatchers("/v2/api-docs")
                .antMatchers("/swagger-resources/**")
                .antMatchers("/webjars/springfox-swagger-ui/**")
                // 静态资源
                .antMatchers("/favicon.ico")
                .antMatchers("/static/img/**")
                .antMatchers("/static/fonts/**")
                .antMatchers("/static/css/**")
                .antMatchers("/static/js/**")
                .antMatchers("/index.html")
                // 业务逻辑
                .antMatchers("/verifyCode");
    }
}
